//
//  XMQHttpFileUploader.m
//  XiaoMiQuan
//
//  Created by liaowei on 14-4-18.
//
//

#import "XMQHttpFileDownloader.h"


@interface XMQHttpFileDownloader ()
{
    long long   expectedContentLength_; // 预计接收数据的总大小
    NSInteger   totalRecvLength_; //已接收的数据感觉有点
}

@end


@implementation XMQHttpFileDownloader

- (id)init
{
    self = [super init];
    if (self != nil) {
        self.delegate = self;
    }
    
    return self;
}

#pragma mark -- XMQHttpFileTransferDelegate

- (void)httpFileTransfer:(NSNumber *)requestId
                 userObj:(id)userObj didFailWithError:(NSError *)error
{
    if (self.downloadDelegate == nil ||
        ![self.downloadDelegate respondsToSelector:@selector(httpDownloadFailWithError:userObj:error:)]) {
        return;
    }
    
    [self.downloadDelegate httpDownloadFailWithError:requestId userObj:userObj error:error];
}

- (void)httpFileTransfer:(NSNumber *)requestId userObj:(id)userObj
         didSendBodyData:(NSInteger)bytesWritten
       totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
}

- (void)httpFileTransfer:(NSNumber *)requestId
                 userObj:(id)userObj didReceiveResponse:(NSURLResponse *)response
{
    totalRecvLength_ = 0;
    expectedContentLength_ = [response expectedContentLength];
    
    if (self.downloadDelegate == nil ||
        ![self.downloadDelegate respondsToSelector:@selector(httpDownloadBegin:userObj:expectedContentLength:)]) {
        return;
    }
    
    [self.downloadDelegate httpDownloadBegin:requestId userObj:userObj
                        expectedContentLength:expectedContentLength_];
}

- (void)httpFileTransfer:(NSNumber *)requestId
                 userObj:(id)userObj didReceiveData:(NSData *)data
{
    if (self.downloadDelegate == nil ||
        ![self.downloadDelegate respondsToSelector:@selector(httpDownloadDidRecvData:userObj:recvLength:totalLength:)]) {
        return;
    }
    
    long long recvLength = [data length];
    totalRecvLength_ += recvLength;
    
    [self.downloadDelegate httpDownloadDidRecvData:requestId userObj:userObj
                                         recvLength:totalRecvLength_
                                        totalLength:expectedContentLength_];
}

- (void)httpFileTransferDidFinishLoading:(NSNumber *)requestId userObj:(id)userObj
{
    if (self.downloadDelegate == nil ||
        ![self.downloadDelegate respondsToSelector:@selector(httpDownloadEnd:userObj:)]) {
        return;
    }
    
    [self.downloadDelegate httpDownloadEnd:requestId userObj:userObj];
}

@end
